from django.shortcuts import render
from django.template.loader import get_template
from django.template import Context
from django.http import HttpResponse
import datetime
from recv.models import shipment_config
import json
from EMC.public import *

# Create your views here.
def shipment_config_admin(request):
    t = get_template('../templates/shipment_config_admin.tpl')
    html = t.render(Context({'current_date': 'ADMIN'}))
    return HttpResponse(html)

def shipment_config_admin_get(request):
    result = []
    table = shipment_config.objects.all()
    for row in table:
        result.append({"SHIPMENT_TYPE_ID":row.SHIPMENT_TYPE_ID,"SHIPMENT_TYPE":row.SHIPMENT_TYPE, "SYSTEM_TYPE":row.SYSTEM_TYPE, "LOCATION":row.LOCATION, "SUB_LOC":row.SUB_LOC,})
    result1 = {"total":len(result),"rows":result}
    return HttpResponse(json.dumps(result1))

def shipment_config_admin_post(request):
    counts = {'inserted':0,'updated':0,'deleted':0}
    error = ""
    try:
        if 'inserted' in request.POST and request.POST['inserted']:
            insertdata = request.POST['inserted']
            if len(insertdata) > 0:
                for row in json.loads(insertdata):
                    insertrow = shipment_config.objects.create(SHIPMENT_TYPE=row["SHIPMENT_TYPE"],SYSTEM_TYPE=row["SYSTEM_TYPE"],LOCATION=row["LOCATION"],SUB_LOC=row["SUB_LOC"])
                    counts['inserted'] +=1

        if 'updated' in request.POST and request.POST['updated']:
            updatedata = request.POST['updated']
            if len(updatedata) > 0:
                for row in json.loads(updatedata):
                    if shipment_config.objects.filter(SHIPMENT_TYPE_ID=row["SHIPMENT_TYPE_ID"]).update(SHIPMENT_TYPE=row["SHIPMENT_TYPE"],SYSTEM_TYPE=row["SYSTEM_TYPE"],LOCATION=row["LOCATION"],SUB_LOC=row["SUB_LOC"])>0:
                        counts['updated'] +=1
        if 'deleted' in request.POST and request.POST['deleted']:
            deletedata = request.POST['deleted']
            if len(deletedata) > 0:
                for row in json.loads(deletedata):
                    shipment_config.objects.filter(SHIPMENT_TYPE_ID=row["SHIPMENT_TYPE_ID"]).delete()
                    counts['deleted'] +=1
    except Exception as e:
        error = e[0]
        print error
    message = CMessage("SHIPMENT_TYPE","Result(Inserted: %d, updated: %d, deleted: %d)" % (counts['inserted'],counts['updated'],counts['deleted']),error)
    return HttpResponse( message.ToJson() )